package com.fastloan.safe.mgt.root.service.impl;

import com.fastloan.safe.mgt.root.dao.CmDefResApiMapper;
import com.fastloan.safe.mgt.root.model.CmDefResApi;
import com.fastloan.safe.mgt.root.model.vo.DefResApiVo;
import com.fastloan.safe.mgt.root.service.CmDefResApiService;
import com.kawins.base.BaseMapper;
import com.kawins.base.baseabs.BaseServiceImpl;
import com.kawins.supers.table.manager.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

@Service
public class CmDefResApiServiceImpl extends BaseServiceImpl<CmDefResApi> implements CmDefResApiService {

    @Autowired
    private CmDefResApiMapper defResApiMapper;

    @Override
    protected BaseMapper<CmDefResApi> buildDao() {
        return defResApiMapper;
    }

    @Override
    protected Logger buildLogger() {
        return LoggerFactory.getLogger(CmDefResApiServiceImpl.class);
    }

    @Override
    @DataTable(name = "defResApiPageList")
    public List<DefResApiVo> pageList(Map<String, Object> map) {
        return defResApiMapper.pageList(map);
    }

    @Override
    public List<CmDefResApi> selectAuthForRoot(String userId) {
        return defResApiMapper.selectAuthForRoot(userId);
    }

    @Override
    public List<CmDefResApi> selectAuth(String userId) {
        List<CmDefResApi> defResApiList = defResApiMapper.selectAuth(userId);
        List<CmDefResApi> apiListByUser = defResApiMapper.selectApiListByUserForAll(userId, true);
        List<CmDefResApi> apiListByUserNoHas = defResApiMapper.selectApiListByUserForAll(userId, false);
        HashSet<String> defApiSet = buildHashSet(defResApiList);
        HashSet<String> apiSet = buildHashSet(apiListByUser);
        HashSet<String> apiSetNoHas = buildHashSet(apiListByUserNoHas);
        defApiSet.addAll(apiSet);
        defApiSet.removeAll(apiSetNoHas);
        Example example = new Example(CmDefResApi.class);
        example.createCriteria().andIn("id", defApiSet);
        return selectByExample(example);
    }

    private HashSet<String> buildHashSet(List<CmDefResApi> defResApiList) {
        HashSet<String> hashSet = new HashSet<>(defResApiList.size());
        for (CmDefResApi cmDefResApi : defResApiList) {
            hashSet.add(cmDefResApi.getId());
        }
        return hashSet;
    }

    @Override
    public List<CmDefResApi> selectAllByValue(String name, String url) {
        return defResApiMapper.selectAllByValue(name, url);
    }

    @Override
    public List<CmDefResApi> selectDefApiResByFunId(String defFunId) {
        return defResApiMapper.selectDefApiResByFunId(defFunId);
    }
}